<script lang="ts" setup>
import { ControlsCard, PaginationCard, SearchCard, TableCard } from '@/components/basic/Card'
import { h, reactive, ref, toRefs } from 'vue'
import { Api } from '@/api/'
import to from '@/utils/awaitTo'
import { AudioOutlined, DownloadOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { PlayAudio } from '@/components/basic/Operation'
import { download } from '@/utils/utils'
import { Pagination } from '@/components/basic/Pagination'


// 响应式数据
const formRef = ref()
const auditRef = ref()
const queryRef = ref()
const state = reactive({
  open: false,
  title: '',
  list: [],
  loading: false,
  total: 0,
  form: {},
  rules: {
    affiliatedPlatform: [{ required: true, message: '请输入音色名称', trigger: 'blur' }],
    doctorId: [{ required: true, message: '请输入音色名称', trigger: 'blur' }],
    timbreReproductionCode: [{ required: true, message: '请输入音色名称', trigger: 'blur' }],
    timbreReproductionName: [{ required: true, message: '请输入音色名称', trigger: 'blur' }],
    trainingVideo: [{ required: true, message: '请输入音色名称', trigger: 'blur' }],
    tripleSpeed: [{ required: true, message: '请输入音色速率', trigger: 'blur' }, {
      pattern: /^(0(\.\d+)?|1(\.\d+)?|2(\.0+)?)$/, message: '输入0-2之间'
    }]
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    nickName: '',
    timbreReproductionName: '',
    timbreReproductionStatus: undefined
  },
  sendLoading: false
})

// 响应式数据解析
const { open, title, list, rules, loading, total, queryParams, form, sendLoading } = toRefs(state)


// 数据列表
const getList = async () => {
  loading.value = true
  const [error, data] = await to(Api.virtual.virtualReproductionList(queryParams.value))
  loading.value = false
  if (!error) {
    // console.log(data)
    list.value = data.rows
    total.value = Number(data.total)
  }
}


// 重置时间
const handleReset = () => {
  queryRef.value.resetFields()
  getList()
}

// 音色复刻新增
const handleAddTimbre = () => {
  reset()
  open.value = true
  title.value = '新增音色复刻'
}

// 音色复刻修改
const handleEditEcho = (item) => {
  reset()
  sendLoading.value = true
  open.value = true
  title.value = '修改音色复刻'
  form.value = item
  sendLoading.value = false
  console.log(item)
}

// 确定
const handleOk = () => {
  formRef.value.validate().then(async (values) => {
    const params = Object.assign({}, form.value, values)

    if (params.timbreReproductionId) {
      let formData = {
        timbreReproductionId: params.timbreReproductionId,
        tripleSpeed: params.tripleSpeed
      }
      const [error, data] = await to(Api.virtual.virtualEditTimbre(formData));

      if (!error) {
        console.log(data)
        message.success(`修改音色复刻`)
        open.value = false
        await getList()
      }
    }

    // 新增
    else {
      if (params.trainingVideo && params.trainingVideo[0] && params.trainingVideo[0].originFileObj) {
        params.trainingVideo = params.trainingVideo[0].originFileObj
      }
      console.log(params)
      let formData = new FormData()
      formData.append('affiliatedPlatform', params.affiliatedPlatform)
      formData.append('cluster', params.cluster)
      formData.append('doctorId', params.doctorId)
      formData.append('timbreReproductionCode', params.timbreReproductionCode)
      formData.append('timbreReproductionName', params.timbreReproductionName)
      formData.append('trainingVideo', params.trainingVideo)
      formData.append('tripleSpeed', params.tripleSpeed)
      sendLoading.value = true
      const [error, data] = await to(Api.virtual.virtualNewTimbre(params))
      sendLoading.value = false
      if (!error) {
        console.log(data)
        message.success(`新增音色复刻`)
        open.value = false
        await getList()
      }
    }


  })
}

// 重置
const reset = () => {
  form.value = {
    timbreReproductionId: '',
    affiliatedPlatform: '',
    doctorId: '',
    timbreReproductionCode: '',
    timbreReproductionName: '',
    tripleSpeed: '',
    cluster: '',
    trainingVideo: []
  }
}


/** 审核数据 */
const auditData = reactive({
  open: false,
  title: '',
  form: {},
  rules: {
    affiliatedPlatform: [
      { required: true, message: '请选择所属平台', trigger: 'change' }
    ],
    reviewComments: [
      { required: true, message: '请选择审核结果', trigger: 'change' }
    ],
    remark: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
    cluster: [{ required: true, message: '请选择所属集群', trigger: 'change' }],
    timbreReproductionCode: [
      { required: true, message: '请选择音色编号', trigger: 'change' }
    ]
  }
})

// 打开
const handleAudit = (item) => {
  console.log(item)
  auditData.open = true
  auditData.title = '审核'
  auditData.form.timbreReproductionId = item.timbreReproductionId
}

// 审核确定确定
const handleAuditSubmit = () => {
  auditRef.value.validate().then(async (values) => {
    const params = Object.assign({}, auditData.form, values)
    console.log(params)
    const { error, data } = await to(Api.virtual.virtualAuditRep(params))
    if (!error) {
      console.log(data)
    }
  })
}


/** 下载 */
const handleDownLoad = async (row) => {
  const [error, data] = await to(Api.virtual.virtualDownLoadSuccess({ timbreReproductionId: row.timbreReproductionId }))
  if (!error) {
    console.log(data)
    download(row.trainingAudio, row.timbreReproductionName)
    await getList()
  }
}

/** 医生列表回显示 */
const dockerData = reactive({
  loading: false,
  list: [],
  queryParams: {
    searchName: ''
  }
})

// 医生列表
const getDockerList = async () => {
  dockerData.loading = true
  const [error, data] = await to(Api.virtual.virtualDoctorList(dockerData.queryParams))
  dockerData.loading = false
  if (!error) {
    dockerData.list = data
  }
}
// 医生搜索
const handleDoctorSearch = (value: string) => {
  dockerData.queryParams.searchName = value
  getDockerList()
}

// 上传图片
const beforeUpload = () => {
  return false
}

/** 表格KEY */
const columns = [
  {
    title: `录制医生`,
    dataIndex: `nickName`,
    key: `nickName`,
    align: `center`
  },
  {
    title: `音色名称`,
    dataIndex: `timbreReproductionName`,
    key: `timbreReproductionName`,
    align: `center`
  },
  {
    title: `音色速率`,
    dataIndex: `tripleSpeed`,
    key: `tripleSpeed`,
    align: `center`
  },
  {
    title: `操作状态`,
    dataIndex: `timbreReproductionStatus`,
    key: `timbreReproductionStatus`,
    align: `center`
  },
  {
    title: `操作`,
    dataIndex: `operation`,
    key: `operation`,
    align: `center`
  }
]

/** 音色复刻状态字典 */
const dictTimbreList = [
  {
    label: '待审核',
    value: '1001',
    listClass: 'warning',
    color: '#f50'
  },
  {
    label: '审核失败',
    value: '1002',
    listClass: 'danger',
    color: '#ec1f1f'
  },
  {
    label: '审核成功',
    value: '1003',
    listClass: 'success',
    color: '#87d068'
  },
  {
    label: '训练中',
    value: '1004',
    listClass: 'success',
    color: '#108ee9'
  },
  {
    label: '已上线',
    value: '1005',
    listClass: 'info',
    color: '#108243'
  }
]

/** 所属平台字典 */
const OwningPlatformDict = [
  {
    label: '腾讯',
    value: '2001'
  },
  {
    label: '标贝',
    value: '2002'
  },
  {
    label: '火山',
    value: '2003'
  }
]

/** 审核状态字典 */
const TopicAuditTypeDict = [
  {
    label: '通过',
    value: '1'
  },
  {
    label: '不通过',
    value: '2'
  }
]


getList()
getDockerList()
</script>

<template>
  <div>
    <!--  搜索  -->
    <SearchCard>
      <a-form ref="queryRef" :model="queryParams" layout="inline">
        <a-form-item label="选择医生" name="userId">
          <a-select v-model:value="queryParams.userId" :fieldNames="{label:'doctorName',value:'userId'}"
                    :options="dockerData.list" placeholder="选择选择医生"
                    show-search style="width: 220px;"
                    @change="getList" />
        </a-form-item>

        <a-form-item label="操作状态" name="timbreReproductionStatus">
          <a-select v-model:value="queryParams.timbreReproductionStatus" :fieldNames="{label:'label',value:'value'}"
                    :options="dictTimbreList"
                    placeholder="选择选操作状态" style="width: 220px;" @change="getList" />
        </a-form-item>

        <a-form-item>
          <a-space>
            <a-button type="primary" @click="getList">查询</a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>

      </a-form>
    </SearchCard>

    <!-- 操作 -->
    <ControlsCard>
      <a-button
        :icon="h(AudioOutlined)"
        :loading="loading"
        type="primary"
        @click="handleAddTimbre"
      >新增音色
      </a-button>
    </ControlsCard>

    <!-- 表格 -->
    <TableCard>
      <a-table :columns="columns" :data-source="list" :loading="loading" :pagination="false">
        <!-- 状态值 -->
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.key === 'timbreReproductionStatus'">
            <div v-for="item in dictTimbreList" :key="item.value">
              <a-tag
                v-if="item.value === text"
                :bordered="true"
                :color="item.color"
              >{{ item.label }}
              </a-tag>
            </div>
          </template>

          <!-- 操作 -->
          <template v-if="column.key === 'operation'">
            <a-space>
              <!-- 播放音频-->
              <PlayAudio :row="{ voiceUrl:record.trainingAudio,topicTitle:record.timbreReproductionName }" />

              <!-- 修改 -->
              <a-button danger type="primary" @click="handleEditEcho(record)">修改</a-button>

              <!-- 审核 -->
              <!--              <a-button v-if="Number(record.timbreReproductionStatus) === 1001" @click="handleAudit(record)">-->
              <!--                审核-->
              <!--              </a-button>-->

              <!-- 下载 -->
              <a-button
                v-if="Number(record.timbreReproductionStatus) === 1003 && Number(record.affiliatedPlatform) !== 2003"
                :icon="h(DownloadOutlined)"
                :loading="sendLoading"
                @click="handleDownLoad(record)"
              >
                下载
              </a-button>


            </a-space>
          </template>
        </template>
      </a-table>
    </TableCard>

    <!-- 分页 -->
    <PaginationCard>
      <Pagination v-model:page-num="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                  :total="total" @pagination="getList" />
    </PaginationCard>


    <!--  音色弹框  -->
    <a-modal v-model:open="open" :ok-button-props="{ loading: sendLoading }" :title="title"
             @ok="handleOk">
      <a-form ref="formRef" :model="form" :rules="rules">
        <a-form-item v-if="!form.timbreReproductionId" label="音色名称" name="affiliatedPlatform">
          <a-radio-group
            v-model:value="form.affiliatedPlatform"
            button-style="solid"
          >
            <a-radio-button
              v-for="item in OwningPlatformDict"
              :key="item.value"
              :value="item.value"
            >{{ item.label }}
            </a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-item v-if="!form.timbreReproductionId" label="选择医生" name="doctorId">
          <a-select
            v-model:value="form.doctorId"
            :fieldNames="{ label: 'doctorName', value: 'userId' }"
            :options="dockerData.list"
            placeholder="选择选择医生"
            show-search
            @search="handleDoctorSearch"
          />
        </a-form-item>

        <a-form-item v-if="!form.timbreReproductionId" label="音色编号" name="timbreReproductionCode">
          <a-input
            v-model:value="form.timbreReproductionCode"
            placeholder="选择音色编号"
          />
        </a-form-item>

        <a-form-item v-if="!form.timbreReproductionId" label="音色名称" name="timbreReproductionName">
          <a-input
            v-model:value="form.timbreReproductionName"
            placeholder="选择音色名称"
          />
        </a-form-item>

        <a-form-item label="音色复刻速率" name="tripleSpeed">
          <a-input v-model:value="form.tripleSpeed" />
        </a-form-item>

        <a-form-item
          v-if="Number(form.affiliatedPlatform) === 2003 && !form.timbreReproductionId"
          label="所属集群"
          name="cluster"
        >
          <a-input
            v-model:value="form.cluster"
            placeholder="请输入所属集群"
          />
        </a-form-item>


        <a-form-item
          v-if="Number(form.affiliatedPlatform) === 2003 && !form.timbreReproductionId"
          label="训练视频音频"
          name="trainingVideo"
        >
          <a-upload
            v-model:fileList="form.trainingVideo"
            :before-upload="beforeUpload"
            :maxCount="1"
            accept=".mp3"
            action="#"
            listType="picture"
            method="post"
          >
            <a-button>上传训练音频</a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>


    <!--  审核弹框  -->
    <a-modal v-model:open="auditData.open" :title="auditData.title" @ok="handleAuditSubmit">
      <a-form ref="auditRef" :model="auditData.form" :rules="auditData.rules">
        <a-form-item label="音色名称" name="affiliatedPlatform">
          <a-radio-group
            v-model:value="auditData.form.affiliatedPlatform"
            button-style="solid"
          >
            <a-radio-button
              v-for="item in OwningPlatformDict"
              :key="item.value"
              :value="item.value"
            >{{ item.label }}
            </a-radio-button
            >
          </a-radio-group>
        </a-form-item>

        <a-form-item label="审核结果" name="reviewComments">
          <a-radio-group v-model:value="auditData.form.reviewComments">
            <a-radio
              v-for="item in TopicAuditTypeDict"
              :key="item.value"
              :value="item.value"
            >{{ item.label }}
            </a-radio
            >
          </a-radio-group>
        </a-form-item>

        <a-form-item
          v-if="Number(auditData.form.reviewComments) === 2"
          label="审核意见"
          name="remark"
        >
          <a-textarea
            v-model:value="auditData.form.remark"
            :rows="4"
            placeholder="这里是审核意见及修改说明文字"
          />
        </a-form-item>
        <a-form-item
          v-if="Number(auditData.form.affiliatedPlatform) === 2003"
          label="音色编号"
          name="timbreReproductionCode"
        >
          <a-input
            v-model:value="auditData.form.timbreReproductionCode"
            placeholder="选择音色编号"
          />
        </a-form-item>

        <a-form-item
          v-if="Number(auditData.form.affiliatedPlatform) === 2003"
          label="所属集群"
          name="cluster"
        >
          <a-input v-model:value="auditData.form.cluster" placeholder="请输入所属集群" />
        </a-form-item>

      </a-form>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>

</style>
